/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    class CompItem : BindInterface
    {
        public CompItem(string name = "")
        {
            Text = name;
        }
        override public System.Windows.Visibility IsVisible
        {
            get
            {
                if (CloseCheck.GlobalStateObject.SystemHasCompAccounts &&
                    !CloseCheck.StateObject.SelectedSaleIsGiftCardSale &&
                    CloseCheck.StateObject.SelectedSaleDiscountIdIsNullOrZero
                    && !CloseCheck.StateObject.SelectedSaleIsForcedModifier
                    && !CloseCheck.StateObject.CanCloseSelectedCheck &&
                    CloseCheck.StateObject.CurrentUserCanCompItem)
                {
                    return System.Windows.Visibility.Visible;
                }
                else
                {
                    return System.Windows.Visibility.Hidden;
                }
            }
        }

        override public void Clicked()
        {
            try
            {
                CloseCheckWindow.StopChangeDueBlink();
                SALE saleToMove = CloseCheckWindow.CustomerTicketListView.SelectedItem as SALE;
                SALE seperate = saleToMove;
                if (saleToMove != null)
                {
                    bool canMove = true;
                    if (saleToMove.CountOrdered > 1)
                    {
                        HowManyBox hmb = new HowManyBox();
                        hmb.ShowDialog();
                        if (HowManyBox.LastNumberSelection > 0 && HowManyBox.LastNumberSelection <= saleToMove.CountOrdered)
                        {
                            if (HowManyBox.LastNumberSelection == saleToMove.CountOrdered)
                            {
                                seperate = saleToMove;
                            }
                            else
                            {
                                seperate = SALE.SeparateSale(saleToMove, true, HowManyBox.LastNumberSelection);
                            }
                        }
                        else
                        {
                            UMD.ShowGuiMessageSTASafe_NOTHROW("You must select an amount greater than zero and less than or equal to "
            + saleToMove.CountOrdered + " for the currently selected product.");
                            canMove = false;
                        }
                    }

                    if (canMove)
                    {
                        CompReasonsByButton crsb =
                            new CompReasonsByButton(SHIFT.GlobalContext.COMP_ACCOUNTS.Where(ca => ca.IsComp && !ca.IsDeleted).ToList());
                        crsb.ShowDialog();

                        if (CompReasonsByButton.LastResponse == UserResponse.ENTER)
                        {
                            COMP_ACCOUNT ca = CompReasonsByButton.ChosenComp;
                            seperate.DiscountId = ca.Id;

                            if (PosWindow.ManagerCardWasSwiped)
                            {
                                seperate.DiscountManagerId = PosWindow.ManagerIdThatSwiped;
                            }
                            else
                            {
                                seperate.DiscountManagerId = SHIFT.Current.UserId;
                            }
                            seperate.OnHold = false;
                            seperate.NoteForPrint = "";
                            SHIFT.SelectedOrder.HasProductsOnHold = false;
                            foreach (SALE s in SHIFT.SelectedOrder.SALES)
                            {
                                if (s.OnHold)
                                {
                                    SHIFT.SelectedOrder.HasProductsOnHold = true;
                                    break;
                                }
                            }

                            seperate.WasCompedInEntire = true;
                            seperate.DiscountRate = 1.0M;

                            foreach (SALE s in seperate.MODSALES)
                            {
                                s.DiscountManagerId = seperate.DiscountManagerId;
                                s.DiscountRate = 1.0M;
                                s.WasCompedInEntire = true;
                                s.DiscountId = seperate.DiscountId;
                            }

                            if (ca.PromptUserToEnterNotes)
                            {
                                Oceanside.FullKeyboard.ActiveKeyboard.SetSmallMode(false);
                                Oceanside.FullKeyboard.ActiveKeyboard.SetMessage("Enter an Explanation:");
                                Oceanside.FullKeyboard.ActiveKeyboard.ShowMe();
                                if (Oceanside.FullKeyboard.LastResponse == UserResponse.ENTER)
                                {
                                    _selSale = seperate;
                                    EnterKeyPressedDelegate(Oceanside.FullKeyboard.GuiKeyPressedString);
                                }
                            }
                            else
                            {
                                SHIFT.GlobalContext.SaveChanges();
                                CCBindings.UpdateTicketFocus();
                                CCBindings.RefreshThreadSafe();
                            }
                        }
                    }
                    CCBindings.RefreshDiscountWindow(true);
                }
                else
                {
                    UMD.ShowGuiMessageSTASafe_NOTHROW("Please select an item to Comp before trying to use this function.");
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CCBIND_CALL_COMPPRODUCT, ex);
            }
        }


        /// <summary>
        /// This is bad practice, but under extreme deadline
        /// </summary>
        private static SALE _selSale = null;
        /// <summary>
        /// 
        /// </summary>
        private static void EnterKeyPressedDelegate(String name)
        {
            if (_selSale != null)
            {
                try
                {
                    _selSale.Notes = name;
                    foreach (SALE s in _selSale.MODSALES)
                    {
                        s.Notes = name;
                    }
                    SHIFT.GlobalContext.SaveChanges();
                    _selSale = null;
                    CCBindings.UpdateTicketFocus();
                    CCBindings.RefreshThreadSafe();
                }
                catch (Exception e)
                {
                    Logging.LogException(e);
                }
            }
        }
    }
}
